import 'package:flutter/material.dart';
import 'package:flutter_deer/game/game_router.dart';
import 'package:flutter_deer/game/models/game_item_entity.dart';
import 'package:flutter_deer/game/page/game_list_page.dart';
import 'package:flutter_deer/game/presenter/game_search_list_presenter.dart';
import 'package:flutter_deer/game/provider/game_page_provider.dart';
import 'package:flutter_deer/game/provider/game_search_list_provider.dart';
import 'package:flutter_deer/mvp/base_page.dart';
import 'package:flutter_deer/mvp/power_presenter.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/routers/fluro_navigator.dart';
import 'package:flutter_deer/util/image_utils.dart';
import 'package:flutter_deer/util/other_utils.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/widgets/load_image.dart';
import 'package:flutter_deer/widgets/my_card.dart';
import 'package:flutter_deer/game/iview/game_search_list_iview.dart';
import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:provider/provider.dart';

class GamePage extends StatefulWidget {

  const GamePage({super.key});

  @override
  _GamePageState createState() => _GamePageState();
}

class _GamePageState extends State<GamePage> with SingleTickerProviderStateMixin,BasePageMixin<GamePage, PowerPresenter>, AutomaticKeepAliveClientMixin implements GameSearchListIMvpView {

  TabController? _tabController;
  final PageController _pageController = PageController();
  GamePageProvider provider = GamePageProvider();
  GameSearchListProvider listProvider = GameSearchListProvider();
  final GlobalKey _bodyKey = GlobalKey();
  late GameSearchListPresenter gameSearchListPresenter;
  List<GameListPage> pages = [];
  @override
  PowerPresenter<dynamic> createPresenter() {
    final PowerPresenter<dynamic> powerPresenter = PowerPresenter<dynamic>(this);
    gameSearchListPresenter = new GameSearchListPresenter();
    powerPresenter.requestPresenter([gameSearchListPresenter]);
    return powerPresenter;
  }

  @override
  void setAllGameItems(List<GameItemEntity>? items){
    listProvider.setGameItems(items);
  }

  @override
  void setGameItems(List<GameItemEntity>? items){
    listProvider.setGameItems(items);
  }

  @override
  void initState() {
    super.initState();
    pages = [GameListPage(index: 2),GameListPage(index: 3),GameListPage(index: 1)];
    _tabController = TabController(vsync: this, length: 3);
  }

  @override
  void dispose() {
    _tabController?.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final Color? iconColor = ThemeUtils.getIconColor(context);
    double textWidth = 0;
    List<String> titles = [DeerLocalizations.of(context)!.gameToday.nullSafe,DeerLocalizations.of(context)!.gameTomorrow.nullSafe,DeerLocalizations.of(context)!.gameHistory.nullSafe];
    for(int i=0;i<titles.length;i++){
      TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: titles.elementAt(i),
        ),
        textDirection: TextDirection.ltr,
      );
      textPainter.layout();
      if(textWidth<textPainter.size.width){
        textWidth = textPainter.size.width;
      }
    }
    return ChangeNotifierProvider<GamePageProvider>(
      create: (_) => provider,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text('${DeerLocalizations.of(context)!.tabGame.nullSafe}',style: TextStyle(fontSize: Dimens.font_sp18,color: context.isDark?Colours.text_gray : Colours.text,)),
          actions: <Widget>[
            IconButton(
              tooltip: '搜索赛事',
              onPressed: () => NavigatorUtils.push(context, GameRouter.gameSearchPage),
              icon: LoadAssetImage(
                'goods/search',
                key: const Key('search'),
                width: 24.0,
                height: 24.0,
                color: iconColor,
              ),
            )
          ]
        ),
        body: Column(
          key: _bodyKey,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              // 隐藏点击效果
              padding: EdgeInsets.only(left: 0.0,right: 0.0),
              color: context.backgroundColor,
              child: TabBar(
                onTap: (index) {
                  if (!mounted) {
                    return;
                  }
                  _pageController.jumpToPage(index);
                },
                isScrollable: true,
                controller: _tabController,
                labelStyle: TextStyles.textBold18,
                indicatorSize: TabBarIndicatorSize.label,
                labelPadding: EdgeInsets.zero,
                unselectedLabelColor: context.isDark ? Colours.text_gray : Colours.text,
                labelColor: Theme.of(context).primaryColor,
                indicatorPadding: EdgeInsets.only(right: 18,left:18),
                tabs: <Widget>[
                  _TabView('${DeerLocalizations.of(context)!.gameToday.nullSafe}', 0,textWidth),
                  _TabView('${DeerLocalizations.of(context)!.gameTomorrow.nullSafe}', 1,textWidth),
                  _TabView('${DeerLocalizations.of(context)!.gameHistory.nullSafe}', 2,textWidth)
                ],
              ),
            ),
            Gaps.line,
            Expanded(
              child: PageView.builder(
                key: Key('pageView'),
                itemCount: 3,
                onPageChanged: _onPageChange,
                controller: _pageController,
                itemBuilder: (_, int index) => pages.elementAt(index)
              )
            )
          ]
        )
      )
    );
  }

  void _onPageChange(int index) {
    if (!mounted) {
      return;
    }
    provider.setIndex(index);
    _tabController?.animateTo(index);
    _pageController.jumpToPage(index);
  }

  Widget buildSearchItem(GameItemEntity item){
    return Padding(
        padding: const EdgeInsets.symmetric(horizontal: 10.0,vertical: 5),
        child: MyCard(
            child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 5),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 5,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(item.name.nullSafe),
                        Text('${DeerLocalizations.of(context)!.playingTime.nullSafe}:'+item!.playDate.nullSafe+' '+item.playTime.nullSafe)
                      ],
                    ),
                    SizedBox(height: 5,),
                    Divider(height: 1.0,indent: 0.0),
                    SizedBox(height: 5,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Column(
                          children: [
                            Image(image:ImageUtils.getImageProvider(Constant.imageServerHost+'${item.teamOne!.image.nullSafe}',holderImg: 'shop/tx'),width: 40,height: 40,),
                            SizedBox(height: 12,),
                            Text(item.teamOneName.nullSafe)
                          ],
                        ),
                        LoadAssetImage('logo',format:ImageFormat.gif,width:50,height:50),
                        Column(
                          children: [
                            Image(image:ImageUtils.getImageProvider(Constant.imageServerHost+'${item.teamTwo!.image.nullSafe}',holderImg: 'shop/tx'),width: 40,height: 40,),
                            SizedBox(height: 12,),
                            Text(item.teamTwoName.nullSafe)
                          ],
                        )
                      ],
                    ),
                    SizedBox(height: 5,),
                  ],
                )
            )
        )
    );
  }

  @override
  bool get wantKeepAlive => false;
}

class _TabView extends StatelessWidget {
  
  const _TabView(this.tabName, this.index,this.maxLabelWidth);
  
  final String tabName;
  final int index;
  final double maxLabelWidth;
  
  @override
  Widget build(BuildContext context) {
    if(maxLabelWidth>MediaQuery.of(context).size.width/3-66) {
      return Tab(
          child: Padding(padding: EdgeInsets.only(left: 10, right: 10),
            child: Text(tabName),
          )
      );
    }else{
      return Tab(
        child: SizedBox(
          width: MediaQuery.of(context).size.width/3-36,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(tabName)
            ],
          ),
        ),
      );
    }
  }
}
